<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Menu;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;

class MenuController extends Controller
{
    /**
     * 菜单列表页面
     */
    public function index(Request $request): View
    {
        $query = Menu::with(['creator', 'dishes']);

        // 搜索功能
        if ($request->filled('search')) {
            $search = $request->input('search');
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('description', 'like', "%{$search}%");
            });
        }

        // 筛选功能
        if ($request->filled('source_type')) {
            $query->where('source_type', $request->input('source_type'));
        }

        if ($request->filled('is_public')) {
            $query->where('is_public', $request->input('is_public') === '1');
        }

        if ($request->filled('is_template')) {
            $query->where('is_template', $request->input('is_template') === '1');
        }

        $menus = $query->orderBy('created_at', 'desc')->paginate(15);

        return view('admin.menus.index', compact('menus'));
    }

    /**
     * 菜单详情页面
     */
    public function show(Menu $menu): View
    {
        $menu->load(['creator', 'dishes.category', 'sourceMenu']);
        
        return view('admin.menus.show', compact('menu'));
    }

    /**
     * 创建菜单页面
     */
    public function create(): View
    {
        $users = User::where('is_active', true)->get();
        $sourceMenus = Menu::where('is_public', true)->get();
        
        return view('admin.menus.create', compact('users', 'sourceMenus'));
    }

    /**
     * 保存新菜单
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'name' => 'required|string|max:100',
            'description' => 'nullable|string',
            'creator_id' => 'required|exists:users,id',
            'source_type' => 'required|in:default,custom',
            'source_id' => 'nullable|exists:menus,id',
            'is_public' => 'boolean',
            'is_template' => 'boolean',
        ]);

        $menu = Menu::create($request->all());

        return redirect()->route('admin.menus.show', $menu)
            ->with('success', '菜单创建成功！');
    }

    /**
     * 编辑菜单页面
     */
    public function edit(Menu $menu): View
    {
        $users = User::where('is_active', true)->get();
        $sourceMenus = Menu::where('is_public', true)->where('id', '!=', $menu->id)->get();
        
        return view('admin.menus.edit', compact('menu', 'users', 'sourceMenus'));
    }

    /**
     * 更新菜单
     */
    public function update(Request $request, Menu $menu): RedirectResponse
    {
        $request->validate([
            'name' => 'required|string|max:100',
            'description' => 'nullable|string',
            'creator_id' => 'required|exists:users,id',
            'source_type' => 'required|in:default,custom',
            'source_id' => 'nullable|exists:menus,id',
            'is_public' => 'boolean',
            'is_template' => 'boolean',
        ]);

        $menu->update($request->all());

        return redirect()->route('admin.menus.show', $menu)
            ->with('success', '菜单更新成功！');
    }

    /**
     * 删除菜单
     */
    public function destroy(Menu $menu): RedirectResponse
    {
        // 检查是否有关联的房间
        if ($menu->rooms()->count() > 0) {
            return redirect()->back()
                ->with('error', '该菜单正在被房间使用，无法删除！');
        }

        $menu->delete();

        return redirect()->route('admin.menus.index')
            ->with('success', '菜单删除成功！');
    }

    /**
     * 切换菜单公开状态
     */
    public function togglePublic(Menu $menu): RedirectResponse
    {
        $menu->update(['is_public' => !$menu->is_public]);

        $status = $menu->is_public ? '公开' : '私有';
        return redirect()->back()
            ->with('success', "菜单已设置为{$status}！");
    }

    /**
     * 切换菜单模板状态
     */
    public function toggleTemplate(Menu $menu): RedirectResponse
    {
        $menu->update(['is_template' => !$menu->is_template]);

        $status = $menu->is_template ? '模板' : '普通';
        return redirect()->back()
            ->with('success', "菜单已设置为{$status}！");
    }

    /**
     * 添加菜品到菜单
     */
    public function addDish(Request $request, Menu $menu): RedirectResponse
    {
        $request->validate([
            'dish_id' => 'required|exists:dishes,id'
        ]);

        $sourceDish = \App\Models\Dish::findOrFail($request->dish_id);
        
        // 检查是否已经有相同名称的菜品在菜单中
        if ($menu->dishes()->where('name', $sourceDish->name)->exists()) {
            return redirect()->back()
                ->with('error', "菜品「{$sourceDish->name}」已经在此菜单中！");
        }

        // 基于源菜品创建新的菜品记录
        $newDish = \App\Models\Dish::create([
            'name' => $sourceDish->name,
            'description' => $sourceDish->description,
            'image' => $sourceDish->image,
            'price' => $sourceDish->price,
            'category_id' => $sourceDish->category_id,
            'tags' => $sourceDish->tags,
            'flavors' => $sourceDish->flavors,
            'cooking_time' => $sourceDish->cooking_time,
            'is_available' => $sourceDish->is_available,
            'is_featured' => $sourceDish->is_featured,
            'sort_order' => $sourceDish->sort_order,
            'menu_id' => $menu->id,
            'creator_id' => $sourceDish->creator_id,
            'source_dish_id' => $sourceDish->id,
            'dish_source' => 'menu',
            'is_public' => false,
        ]);

        return redirect()->back()
            ->with('success', "菜品「{$newDish->name}」已成功添加到菜单！");
    }
}